package com.cad3d.filemanager.action;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;

import com.cad3d.filemanager.dao.User;
import com.cad3d.filemanager.dbutils.UserTableTool;
import com.cad3d.filemanager.utils.StringUtils;
import com.opensymphony.xwork2.ActionSupport;

/**
 * 
 * @author cao
 * 
 */

public class LoginAction extends ActionSupport {
	
	private Logger logger = Logger.getLogger(LoginAction.class);
	private static final long serialVersionUID = 1L;
	private String username;
	private String password;
	private User user;

	public String execute() {
		ServletActionContext.getRequest().getSession()
				.setAttribute("loggedInUser", user);
		
		logger.debug("============LOGIN==========");
		logger.debug("USER:" + username);
		logger.debug("============END LOGIN==========");
		
		return "success";
	}

	public void validate() {
		
		user = (User) ServletActionContext.getRequest().getSession()
				.getAttribute("loggedInUser");

		if (StringUtils.isNullOrEmpty(user)) {
			if (StringUtils.isNullOrEmpty(username)) {
				addFieldError("username", getText("errors.userreq"));
			} else if (StringUtils.isNullOrEmpty(password)) {
				addFieldError("password", getText("errors.passreq"));
			} else {
				user = UserTableTool.getInstance().getUserByUsername(username);
				if (StringUtils.isNullOrEmpty(user)) {
					addFieldError("username", getText("errors.invalid"));
				} else {
					if (!password.equals(user.getPassword())) {
						addFieldError("username", getText("errors.invalid"));
					}
				}
			}
		}
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

}
